<template>
  <div ref="map" style="height: 100%"></div>
</template>

<script>
import { get } from "@/utils/request";
// 引入辅助函数
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      empData: [],
    };
  },

  methods: {
    // 解构方法
    ...mapMutations(['SET_ED']),
    async getEmp() {
      let res = await get("/dashboard/findEngineerDeviceTree");
      // console.log(res,'----');
      let temp = [];
      res.data.forEach((item) => {
        item.children.forEach((it) => {
          temp.push(it);
          // console.log(temp,'----');
          this.empData = temp;
        });
      });
      this.drawMap();

    },
    drawMap() {
      var map = new AMap.Map(this.$refs.map, {
        mapStyle: "amap://styles/blue", //设置地图的显示样式
        zoom: 11, //级别
        center: [103.839949, 36.069335], //中心点坐标
        viewMode: "3D", //使用3D视图
      });
      this.empData.forEach((item) => {
        var marker = new AMap.Marker({
          position: item.position, //位置
          icon: "http://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png",
          title: item.name,
          anchor: "bottom-left", // 设置锚点方位
          extData: item,
        });
        // 将组件实例赋值给vm
        let vm=this;
        marker.on("click", function () {
          vm.SET_ED({
            engineer_id: this.getExtData().engineer_id,
            device_id:this.getExtData().id
          })
          // console.log(this.getExtData(), "-----");
        });
        map.add(marker); //添加到地图
      });

      let polygons = [];
      var opts = {
        subdistrict: 0, //获取边界不需要返回下级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "district", //查询行政级别为 市
      };
      let district = new AMap.DistrictSearch(opts);
      district.setExtensions("all");
      district.search("兰州市", function (status, result) {
        map.remove(polygons); //清除上次结果
        polygons = [];
        var bounds = result.districtList[0].boundaries;
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
              strokeWeight: 5,
              path: bounds[i],
              fillOpacity: 0.4,
              fillColor: "#80d8ff",
              strokeColor: "#0091ea",
            });
            polygons.push(polygon);
          }
        }
        map.add(polygons);
        map.setFitView(polygons); //视口自适应
      });
    },
  },

  mounted() {
    // this.drawMap();
    this.getEmp();
  },
};
</script>

<style>
.amap-icon img {
  width: 24px;
  height: 30px;
}
</style> 